<script src="lib/js/zepto.min.js"></script>
<script charset="utf-8" src="http://map.qq.com/api/js?v=2.exp"></script>
<script>

    (function ($, window) {
        //note:
        //setMapLabel:经纬度设置标签
        //calcPlan:公交路线
        var oMap = null;
        var defultLoc = {
            lat: 23.120153100000002, lon: 113.32599999999999, val: "初始地图中心位置"
        }
        var loc1 = {
            lat: 23.139963100000002, lon: 113.24441499999999, val: "loc1旗舰店"
        }
        var loc2 = {
            lat: 23.119163300000012, lon: 113.29441499999999, val: "天河旗舰店"
        }
        var usrLoc = {
            lat: null, lon: null, val: "您在这里"
        }
        var transfer_plans,
            //start_marker,
            //end_marker,
            station_markers = [],
            transfer_lines = [],
            walk_lines = [],
            directions_routes,

            directions_placemarks = [],
            directions_labels = [],
            route_lines = [],
            step_line,
            route_steps = [];
        var transferService = fTransferService("广州");
        var drivingService = fDrivingService("广州");
        //load
        $(function ($) {
            var oMapCanvas = $("#map_canvas")[0];
            oMap = getMaps(oMapCanvas, defultLoc.lat, defultLoc.lon, function (map) {
                var sVal1 = getLabelCont(loc1.val);
                var sVal2 = getLabelCont(loc2.val);
                var sVal3 = getLabelCont(defultLoc.val);
                setMapLabel(map, defultLoc.lat, defultLoc.lon, sVal3);
                setMapLabel(map, loc1.lat, loc1.lon, sVal1);
                setMapLabel(map, loc2.lat, loc2.lon, sVal2);
                //获取用户位置:
                getUsrLocation(function (lat, lon) {
                    //$("#log").html(lat);$("#log2").html(lon);
                    usrLoc.lat = lat;
                    usrLoc.lon = lon;
                    var sVal0 = getLabelCont("您在这里");
                    setMapLabel(map, lat, lon, sVal0);
                    map.setCenter(new qq.maps.LatLng(lat, lon))
                });
            });
            //calcPlan(usrLoc, loc1);
            
        });
        //oMapCanvas:容器
        //lat,lon 地图显示中心位置的经纬度
        //call:获取map后的回调,参数为map对象
        function getMaps(oMapCanvas, lat, lon, call){
            var loc = new qq.maps.LatLng(lat, lon);
            var map = new qq.maps.Map(oMapCanvas, {
                // 地图的中心地理坐标。
                center: loc,
                zoom: 13,
                disableDefaultUI: true
            });
            if (call) { call(map); }
            return map;
           
        }
        //获取插入map label内容的样式
        function getLabelCont(val) {
            return "<div style='padding-right:10px;'>" + val + "</div>";
        }
        //在地图添加标签,
        //map:map对象,
        //lat, lon:标签所指坐标
        function setMapLabel(map, lat, lon, content) {
            var loc = new qq.maps.LatLng(lat, lon);
            var infoWin = new qq.maps.InfoWindow({
                map: map
            });
            infoWin.open();
            infoWin.setContent(content);
            infoWin.setPosition(loc);
        }
        //call:返回经纬度
        function getUsrLocation(call) {
            if (!navigator.geolocation) {
                handleNoGeolocation("不支持HTML5");
                return;
            }
            navigator.geolocation.getCurrentPosition(function (position) {
                //成功
                if (!call) { return; }
                call(position.coords.latitude, position.coords.longitude);
            }, function (msg) {
                //出错
                
                handleNoGeolocation(msg.message);
                return;
            });
        }
        function handleNoGeolocation(msg) {
            alert(msg);
        }
        //返回公交线路对象,传入city(好似无意义)
        function fTransferService(city) {
           return new qq.maps.TransferService({
               location: city,
                complete: function (result) {
                    result = result.detail;
                    var start = result.start,
                          end = result.end;
                    var anchor = new qq.maps.Point(6, 6),
                        size = new qq.maps.Size(24, 36),
                        start_icon = new qq.maps.MarkerImage(
                            'images/busmarker.png',
                            size
                        ),
                        end_icon = new qq.maps.MarkerImage(
                            'images/busmarker.png',
                            size,
                            new qq.maps.Point(24, 0),
                            anchor
                        );
                    //文字描述
                    transfer_plans = result.plans;
                    getRountguide(transfer_plans);

                    //渲染到地图上
                    renderPlan(0);
                }
            });
        }
        //返回自驾线路对象,complete里完成线路绘制/文字写入
        function fDrivingService(city) {
            return new qq.maps.DrivingService({
                location: city,
                complete: function (response) {
                    var start = response.detail.start,
                        end = response.detail.end;

                    var anchor = new qq.maps.Point(6, 6),
                        size = new qq.maps.Size(24, 36);
                    
                    clearOverlay(route_lines);
                    clearOverlay(station_markers);
                    clearOverlay(transfer_lines);
                    clearOverlay(walk_lines);
                    directions_routes = response.detail.routes;
                    var routes_desc = [];
                    //所有可选路线方案
                    for (var i = 0; i < directions_routes.length; i++) {
                        var route = directions_routes[i],
                            legs = route;
                        //调整地图窗口显示所有路线    
                        oMap.fitBounds(response.detail.bounds);
                        //所有路程信息            
                        //for(var j = 0 ; j < legs.length; j++){
                        var steps = legs.steps;
                        route_steps = steps;
                        polyline = new qq.maps.Polyline({
                                path: route.path,
                                strokeColor: '#3893F9',
                                strokeWeight: 6,
                                map: oMap
                            }
                        )
                        route_lines.push(polyline);
                        //所有路段信息
                        for (var k = 0; k < steps.length; k++) {
                            var step = steps[k];
                            //路段途经地标
                            directions_placemarks.push(step.placemarks);
                            //转向
                            var turning = step.turning,
                                img_position;;
                            switch (turning.text) {
                                case '左转':
                                    img_position = '0px 0px'
                                    break;
                                case '右转':
                                    img_position = '-19px 0px'
                                    break;
                                case '直行':
                                    img_position = '-38px 0px'
                                    break;
                                case '偏左转':
                                case '靠左':
                                    img_position = '-57px 0px'
                                    break;
                                case '偏右转':
                                case '靠右':
                                    img_position = '-76px 0px'
                                    break;
                                case '左转调头':
                                    img_position = '-95px 0px'
                                    break;
                                default:
                                    mg_position = ''
                                    break;
                            }
                            var turning_img = '&nbsp;&nbsp;<span' +
                                ' style="margin-bottom: -4px;' +
                                'display:inline-block;background:' +
                                'url(images/turning.png) no-repeat ' +
                                img_position + ';width:19px;height:' +
                                '19px"></span>&nbsp;';
                            var p_attributes = ""
                            routes_desc.push('<p ' + p_attributes + ' ><b>' + (k + 1) +
                            '.</b>' + turning_img + step.instructions);
                        }
                    }
                    //方案文本描述
                    var routes = document.getElementById('router_show_drive');
                    routes.innerHTML = routes_desc.join('<br>');
                }
            })
        }
        //公交线路文字描述
        function getRountguide(transfer_plans) {
            var plans_desc = [];
            for (var i = 0; i < 1; i++) {//transfer_plans.length
                //plan desc.
                var p_attributes = "";
                var actions = transfer_plans[i].actions;
                for (var j = 0; j < actions.length; j++) {
                    var action = actions[j],
                          img_position;
                    action.type == qq.maps.TransferActionType.BUS && (
                        img_position = '-38px 0px'
                    );
                    action.type == qq.maps.TransferActionType.SUBWAY && (
                        img_position = '-57px 0px'
                    );
                    action.type == qq.maps.TransferActionType.WALK && (
                        img_position = '-76px 0px'
                    );

                    var action_img = '<span style="margin-bottom: -4px;' +
                    'display:inline-block;background:url(images/busicon.png) ' +
                    'no-repeat ' + img_position +
                    ';width:19px;height:19px"></span>&nbsp;&nbsp;';
                    plans_desc.push(action_img + action.instructions);
                }
            }
            //方案文本描述
            document.getElementById('router_show').innerHTML = plans_desc.join('<br><br>');
        }
        //绘制公交图层
        function renderPlan(index) {
            var plan = transfer_plans[index],
                  lines = plan.lines,
                  walks = plan.walks,
                  stations = plan.stations;
            oMap.fitBounds(plan.bounds);

            //clear overlays;
            clearOverlay(route_lines);
            clearOverlay(station_markers);
            clearOverlay(transfer_lines);
            clearOverlay(walk_lines);
            var anchor = new qq.maps.Point(6, 6),
                  size = new qq.maps.Size(24, 36),
                  bus_icon = new qq.maps.MarkerImage(
                    'images/busmarker.png',
                    size,
                    new qq.maps.Point(48, 0),
                    anchor
                  ),
                 subway_icon = new qq.maps.MarkerImage(
                    'images/busmarker.png',
                    size,
                    new qq.maps.Point(72, 0),
                    anchor
                 );
            //draw station marker
            for (var j = 0; j < stations.length; j++) {
                var station = stations[j];
                if (station.type == qq.maps.PoiType.SUBWAY_STATION) {
                    var station_icon = subway_icon;
                } else {
                    var station_icon = bus_icon;
                }
                var station_marker = new qq.maps.Marker({
                    icon: station_icon,
                    position: station.latLng,
                    map: oMap,
                    zIndex: 0
                });
                station_markers.push(station_marker);
            }

            //draw bus line
            for (var j = 0; j < lines.length; j++) {
                var line = lines[j];
                var polyline = new qq.maps.Polyline({
                    path: line.path,
                    strokeColor: '#3893F9',
                    strokeWeight: 6,
                    map: oMap
                });
                transfer_lines.push(polyline);
            }

            //draw walk line
            for (var j = 0; j < walks.length; j++) {
                var walk = walks[j];
                var polyline = new qq.maps.Polyline({
                    path: walk.path,
                    strokeColor: '#3FD2A3',
                    strokeWeight: 6,
                    map: oMap
                });
                walk_lines.push(polyline);
            }
        }
        //公交路线请求
        function calcPlan(start_loc, end_loc) {
            transferService.search(new qq.maps.LatLng(start_loc.lat, start_loc.lon), new qq.maps.LatLng(end_loc.lat, end_loc.lon));
            //case "较快捷":
            transferService.setPolicy(0);
              
        }
        //驾车路线请求
        function calcRoute(start_loc, end_loc) {
            drivingService.search(new qq.maps.LatLng(start_loc.lat, start_loc.lon), new qq.maps.LatLng(end_loc.lat, end_loc.lon));
            drivingService.setPolicy(0);
        }

        //清除地图上的marker
        function clearOverlay(overlays) {
            var overlay;
            while (overlay = overlays.pop()) {
                overlay.setMap(null);
            }
        }
        //地图缩放
        function setZoom(map,InorOut) {
            var zoom = map.getZoom();
            InorOut == "in" ? map.setZoom(++zoom) : map.setZoom(--zoom);
            
        }
        //event bind
        $(document).on("click", "#map_driveToThere", function () {
            calcRoute(usrLoc, loc2);
            $(".routeGuide-drive-toggler").removeClass("hide");
            $(".routeGuide-toggler").addClass("hide");
            $(this).parents(".modal").removeClass("in");
        });
        $(document).on("click", "#map_publicToThere", function () {
            calcPlan(usrLoc, loc2);
            $(".routeGuide-toggler").removeClass("hide");
            $(".routeGuide-drive-toggler").addClass("hide");
            $(this).parents(".modal").removeClass("in");
        });
        $(document).on("click", "#mapZoomIn", function () {
            setZoom(oMap, "in");
        });
        $(document).on("click", "#mapZoomOut", function () {
            setZoom(oMap, "out");
        });
    })(Zepto, window);



</script>
